package com.teamsun.util;

import com.teamsun.entity.TokenCheckResult;
import io.jsonwebtoken.*;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <p>报表工具平台提供的报表供不同的系统使用</p>
 * <p>如果访问报表需要做权限控制,报表工具通过提供token实现权限的控制</p>
 */
public class RptToken {
    /**
     * 签发JWT
     * @param id
     * @param subject
     * @return
     * @throws Exception
     */
    public static String createJWT(String id, String issuer, String subject, long ttlMillis) {
        //我们将用我们的ApiKey secret来签名我们的JWT
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        //我们将用我们的ApiKey secret来签名我们的JWT  test
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(Constants.JWT_SECERT);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

        //让我们设置JWT索赔
        /*JwtBuilder builder = Jwts.builder().setId(id)
                .setIssuedAt(now)
                .setSubject(subject)
                .setIssuer(issuer)
                .signWith(signatureAlgorithm, signingKey);*/

        JwtBuilder builder = Jwts.builder().setId(id)
                .signWith(signatureAlgorithm, signingKey);

        //已经被指定了，让我们把过期的时间加到
        /*if (ttlMillis >= 0) {
            long expMillis = nowMillis + ttlMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp);
        }*/

        //构建JWT并将其序列化为一个紧凑的、url安全的字符串
        return builder.compact();
    }

    /**
     * 验证JWT
     * @param jwtStr
     * @return
     */
    public static TokenCheckResult validateJWT(String jwtStr) {
        TokenCheckResult checkResult = new TokenCheckResult();
        Claims claims = null;
        try {
            claims = parseJWT(jwtStr);
            checkResult.setSuccess(true);
            checkResult.setClaims(claims);
        } catch (ExpiredJwtException e) {
            checkResult.setErrorCode(Constants.JWT_ERRCODE_EXPIRE);
            checkResult.setSuccess(false);
        } catch (SignatureException e) {
            checkResult.setErrorCode(Constants.JWT_ERRCODE_FAIL);
            checkResult.setSuccess(false);
        } catch (Exception e) {
            checkResult.setErrorCode(Constants.JWT_ERRCODE_FAIL);
            checkResult.setSuccess(false);
        }
        return checkResult;
    }

    /**
     *
     * 解析JWT字符串
     * @param jwt
     * @return
     * @throws Exception
     */
    public static Claims parseJWT(String jwt) throws Exception {
        Claims claims = Jwts.parser()
                .setSigningKey(DatatypeConverter.parseBase64Binary(Constants.JWT_SECERT))
                .parseClaimsJws(jwt).getBody();
        return claims;
    }

    public static void main(String[] args) {
        /*String token = RptToken.createJWT(Constants.JWT_SD_HR,"","",10000);
        System.out.println(token);*/

        String token = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJhdXRoU3lzIn0.DSucRsJyDe5_3CJeNXIApVuuWJKgikJoGZihRoloX-E";
        TokenCheckResult checkResult = RptToken.validateJWT(token);
        System.out.println(checkResult.isSuccess());
        if(checkResult.isSuccess()) {
            System.out.println(checkResult.getClaims().getId());
            Date date = checkResult.getClaims().getExpiration();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if(date != null) {
                System.out.println(format.format(date));
            }
        }

        String str1 = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJhdXRoU3lzIn0.DSucRsJyDe5_3CJeNXIApVuuWJKgikJoGZihRoloX-E";
        String str2 = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJzZEhSIn0.ZgHArTbrZriogZI4QRZNaXU1uArRaeRfzpXuzTV6XSU";
        System.out.println(str1.length());
    }
}
